#!/usr/bin/php -q
<?php
    define('EXPONENT', "ABSoft - Auto Mailling System");
    date_default_timezone_set("Asia/Ho_Chi_Minh");
    include("func.php");
    define('BASE',__realpath(dirname(__FILE__)).'/../');
    include("../conf/config.php");
    // inital the database connection
    require_once("../subsystems/database.php");
    require_once(BASE.'subsystems/mail.php');
    $db = exponent_database_connect(DB_USER,DB_PASS,DB_HOST.':'.DB_PORT,DB_NAME);
    $where = "1";
    $user_list="SELECT * 
    FROM {$db->prefix}mailsystem_mail 
    WHERE {$where} ORDER BY id LIMIT 0,5"; 
    $mail= new exponentMail();
    $users=$db->selectObjectsBySql($user_list);
    $to_email[]=null;
    
    foreach($users as $k=>$v)
    {
        if($to_email[$v->email_id]==null)
        {
            $email=$db->selectObject('mailsystem_email',"email='".$v->email_to."'");
            $to_email[$v->email_id]=$email;
        }
        else
            $email=$to_email[$v->email_id];
        if($email->block==0)
        {
            $error=false;
            try
            {
                if($v->email_from_name=="")
                {
                    $v->email_from_name=SITE_TITLE;
                }
               
                $sending=$mail->real_send($v->subject, $v->content, $v->mail_type , $email->email, true,$v->email_from,$v->email_from_name);
                
                if($sending)
                {
                    $v->date_send=time();
                    unset($v->id);
                    $db->insertObject($v,'mailsystem_mail_sent');
                    $db->delete('mailsystem_mail',' id='.$v->id);
                    $log=null;
                    $log->type='success';
                    $log->date=time();
                    $log->email=$email->email;
                    $log->description="Success send mail to {$email->email}";
                    $db->insertObject($log,'mailsystem_log');
                }
                else
                    $error=true;
            }
            catch(Exception $e)
            {
                $error=true;
                $error_log=$e;
            }
        }
        else
        {
            $error=true;
            $error_log=$email->email." has been block!";
        }
        if($error)
        {
            $log=null;
            $log->type='error';
            $log->date=time();
            $log->email=$email->email;
            $log->description=$error_log;
            $db->insertObject($log,'mailsystem_log');
            $email->count_error++;
            if($email->count_error>5)
            {
                $email->block=1;
                //$email->count_error=0;
            }              
            $db->updateObject($email,'mailsystem_email',' id='.$email->id);
            $db->insertObject($v,'mailsystem_mail_error');
            $db->delete('mailsystem_mail',' id='.$v->id);
            
        }
    }
    // send mail

    echo "OK";
?>
